package com.ocom.payconfig.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.payconfig.EntityMqttOperationProcess;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payconfig.dao.IDaoMqttOrder;
import com.ocom.payconfig.service.MqttOperationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class MqttOperationServiceImpl extends ServiceImpl<IDaoMqttOrder, EntityMqttOperationProcess> implements MqttOperationService {


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE,companyId = "comId")
    public boolean save(Long comId, EntityMqttOperationProcess entityMqttOperationProcess) {
        return super.save(entityMqttOperationProcess);
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public EntityMqttOperationProcess selectMqttProcess(Long companyId, EntityMqttOperationProcess process, List<Integer> status) {
        return this.getOne(Wrappers.lambdaQuery(EntityMqttOperationProcess.class)
                .eq(EntityMqttOperationProcess::getComId,process.getComId())
                .eq(EntityMqttOperationProcess::getMqttDeviceId,process.getMqttDeviceId())
                .eq(EntityMqttOperationProcess::getOrderId,process.getOrderId())
                .in(EntityMqttOperationProcess::getState,status)
                .last("limit 1")
        );
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE)
    public EntityMqttOperationProcess selectMqttProcess(Long companyId, EntityMqttOperationProcess process) {
        return this.getOne(Wrappers.lambdaQuery(EntityMqttOperationProcess.class)
                .eq(EntityMqttOperationProcess::getComId,companyId)
                .eq(ObjectUtil.isNotEmpty(process.getOrderNo()),EntityMqttOperationProcess::getOrderNo,process.getOrderNo())
                .eq(ObjectUtil.isNotEmpty(process.getMqttDeviceId()),EntityMqttOperationProcess::getMqttDeviceId,process.getMqttDeviceId())
                .eq(ObjectUtil.isNotEmpty(process.getMqttDeviceSub()),EntityMqttOperationProcess::getMqttDeviceSub,process.getMqttDeviceSub())
                .eq(ObjectUtil.isNotEmpty(process.getOrderId()),EntityMqttOperationProcess::getOrderId,process.getOrderId())
                .last("limit 1")
        );
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.MASTER)
    public boolean update(Long companyId, EntityMqttOperationProcess process) {
        return this.updateById(process);
    }

    @Override
    public List<EntityMqttOperationProcess> getTimerMqttOrder(Integer orderState) {
        Integer sec = 600;
        if(orderState == 11){
            sec = 600;
        }else if(orderState == 13){
            sec = 120;
        }else if(orderState == 31){
            sec = 90;
        }
        List<EntityMqttOperationProcess> resultList = new ArrayList<>();
        List<EntityMqttOperationProcess> listA = this.getTimerMqttOrder(100L,orderState,sec);
        List<EntityMqttOperationProcess> listB = this.getTimerMqttOrder(600L,orderState,sec);
        if(ObjectUtil.isNotEmpty(listA)){
                resultList.addAll(listA);
        }

        if(ObjectUtil.isNotEmpty(listB)){
            if(ObjectUtil.isEmpty(resultList)){
                resultList.addAll(listB);
            }else{
                Map<Integer,Long> map = new HashMap<>();
                resultList.forEach(process -> {
                    map.put(process.getId(), process.getComId());
                });
//                for
                listB.forEach(process -> {
                    if(ObjectUtil.isEmpty(map.get(process.getId()))){
                        resultList.add(process);
                    }
                });
            }

        }

//        for (int i=0;i<2;i++){
//            Long companyId = i==0?1L:600L;
//            log.info("companyId：{}",companyId);
//
//            if(ObjectUtil.isNotEmpty(list)){
//                resultList.addAll(list);
//            }
//        }
        return resultList;
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE,companyId = "companyId")
    public List<EntityMqttOperationProcess> getTimerMqttOrder(Long companyId, Integer orderState, Integer sec) {
//        log.info("当前companyId是{}",companyId);
        return this.list(Wrappers.lambdaQuery(EntityMqttOperationProcess.class)
                .eq(EntityMqttOperationProcess::getState,orderState)
                .lt(EntityMqttOperationProcess::getUpdateTime, DateUtil.offset(new Date(), DateField.SECOND, -sec)));
    }

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB,isMaster = MasterSlaveEnum.SLAVE,companyId = "companyId")
    public Integer getMaxOrderId(Long companyId) {
        QueryWrapper<EntityMqttOperationProcess> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("Max(`order_id`) as order_id");
        List<Map<String,Object>> results = listMaps(queryWrapper);
        return Optional.ofNullable(results.get(0))
                .map(map -> Integer.valueOf(map.get("order_id").toString()))
                .orElse(0);
    }
}
